﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using System.Threading;

namespace B4ALL.Common
{
    public class Context
    {

        public static T GetContext<T>() where T: IContext, new()
        {
            try
            {
                T context = new T();

                if (HttpContext.Current != null)
                {
                    if (HttpContext.Current.Items.Contains(context.CONTEXT_NAME))
                        return (T)HttpContext.Current.Items[context.CONTEXT_NAME];
                }
                else
                {
                    LocalDataStoreSlot myData = Thread.GetNamedDataSlot(context.CONTEXT_NAME);
                    return (T)Thread.GetData(myData);
                }

                return default(T);
            }
            catch (Exception e)
            {
                B4ALL.Exceptions.ExceptionPolicy.HandleException(e, "Critical Error Policy");

                return default(T);
            }
        }

        public static void SetContext(IContext context)
        {
            if (HttpContext.Current != null)
            {
                if (!HttpContext.Current.Items.Contains(context.CONTEXT_NAME))
                    HttpContext.Current.Items.Add(context.CONTEXT_NAME, context);
                else
                    HttpContext.Current.Items[context.CONTEXT_NAME] = context;
            }
            else
            {
                LocalDataStoreSlot myData = Thread.GetNamedDataSlot(context.CONTEXT_NAME);
                Thread.SetData(myData, context);
            }
        }

    }

    public interface IContext
    {
        String CONTEXT_NAME { get; }
    }
}
